import {
    View,
    Search,
    Popup,
    Cell,
    Tabs,
    Tab,
} from '@hips/vue-ui'
import { getEnvParams, getUrl } from '../../tools/index'
import { getMenuList } from '../../tools/index'
import { munusGetFuncs } from '../../tools/index'
import { getUserInfo, getAllTenant, getAllRoles, putRole, getAppList, getExit } from '../../request/api'
import style from './applications.module.less'
import PopLeft from '../../components/pop-left/index'
import IMGsuccess from '../../assets/radio.png'
import IMGbackground from '../../assets/background.png'
import IMGswitchTip from '../../assets/switch.png'
import IMGsearch from '../../assets/search.svg'
import IMGexit from '../../assets/delete.svg'
import IMGclear from '../../assets/clear.png'
import IMGdefault from '../../assets/func-icon.png'
import IMGuser from '../../assets/user-photo.png'
export default {
    components: {
        PopLeft,
    },
    data () {
        return {
            showTent: false,
            showSearch: false,
            showRole: false,
            userParams: {
                imageUrl: '',
                currentRoleName: '',
                realName: '',
                tenantName: '',
                id: '',
                currentRoleId: "",
                loginName: "",
                phone: "",
                email: "",
            },
            keyWord: "",
            initArr: [],
            includeArr: [],
            tentArr: [],
            roleArr: [],
            arr: [],
            secondMenu: [],
            thirdMenu: [],
            replaceReg: "",
            replaceContent: "",
            showExit: false,
        }
    },
    watch: {
        keyWord: {
            deep: true,
            immediate: true,
            handler (val) {
                while (this.includeArr.length > 0) {
                    this.includeArr.shift()
                }
                if (val !== '') {
                    this.replaceReg = new RegExp(val, 'g');
                    this.replaceContent = '<span style="color: #0840F8">' + val + '</span>'
                    this.initArr.forEach((value) => {
                        if (value.name.includes(val)) {
                            let includeItem = value.name.replace(this.replaceReg, this.replaceContent);
                            let obj = { name: includeItem, funcUrl: value.funcUrl || IMGdefault }
                            this.includeArr.push(obj)
                        }
                    })
                }
            },
        },
    },
    mounted () {
        this.init()
    },
    methods: {
        async init () {
            this.userInfo()
        },
        /**
         * 获取所有角色
         */
        async getAllRoles () {
            while (this.roleArr.length > 0) {
                this.roleArr.shift()
            }
            const res = await getAllRoles();
            const { currentRoleName } = this.userParams
            res.forEach((item) => {
                let selected = false;
                if (item.name === currentRoleName) {
                    selected = true
                }
                this.roleArr.push({ value: item.name, code: item.id, selected })
            })
        },
        /**
         * 获取所有租户
         */
        async getAllTenant () {
            while (this.tentArr.length > 0) {
                this.tentArr.shift()
            }
            const { tenantName } = this.userParams
            const res = await getAllTenant();
            res.forEach((item) => {
                let selected = false;
                if (item.tenantName === tenantName) {
                    selected = true
                }
                this.tentArr.push({ value: item.tenantName, code: item.tenantId, selected })
            })

        },

        async changRole (index, code) {
            this.roleArr.forEach((item) => {
                item.selected = false;
            })
            this.roleArr[index].selected = true;
            try {
                let putRoleUrl = `/iam/v1/users/roles?roleId=${code}`
                await putRole(putRoleUrl)
                await this.userInfo()
                this.showRole = false;
            } catch (error) {
                this.$hips.toast('服务异常')
            }
        },
        showTentpop () {
            this.getAllTenant()
            this.showTent = true;
        },
        changeRole () {
            this.getAllRoles()
            this.showRole = true;
        },
        exitClick () {
            this.showExit = !this.showExit
        },
        async exitLogin () {
            let token = getEnvParams().token
            const url = getUrl()
            try {
                let url = `oauth/logout?access_token=${token}`
                await getExit(url)
            } catch (error) {
                localStorage.clear()
                location.href = url
            }
        },
        funcsclick () {
            //todo
        },
        userInfo () {
            getUserInfo().then((res) => {
                const key = Object.keys(this.userParams)
                for (let item of key) {
                    this.userParams[item] = res[item]
                }
                this.getAppList()
            }).catch((e) => {
                const url = getUrl()
                if (e.response.status === 401) {
                    this.$hips.toast('登录过期重新认证')
                    location.href = url
                } else {
                    this.$hips.toast('服务异常')
                }
            })

        },
        getAppList () {

            getAppList(this.userParams.currentRoleId).then((res) => {
                if (res && res.length > 0) {
                    let envData = JSON.parse(process.env.VUE_APP_TARGET_FUNCTIONIDS)
                    envData = Array.isArray(envData) ? envData : []
                    this.arr = getMenuList(res, envData)
                    this.initArr = munusGetFuncs(this.arr)
                    // 处理选项
                    for (let i = 0; i < this.arr.length; i++) {
                        if (this.arr[i].menus.length > 0) {
                            this.$set(this.secondMenu, i, 0)
                        }
                    }
                    for (let i = 0; i < this.arr.length; i++) {
                        if (this.arr[i].menus.length > 0) {
                            this.$set(this.thirdMenu, i, [])
                            this.arr[i].menus.map((item, index) => {
                                if (item.menus.length > 0) {
                                    this.$set(this.thirdMenu[i], index, 0)
                                }
                            })
                        }
                    }
                } else {
                    this.arr = [];
                    this.initArr = [];
                    return
                }
            }).catch((e) => {
                this.arr = [];
                this.$hips.toast(e)
            })

        },
        changeSearch () {
            this.showSearch = !this.showSearch
        },
    },
    render () {
        const { realName, imageUrl, currentRoleName } = this.userParams;
        return (
            <div class="root">
                <View>
                    <div class={style.content}>
                        <div class={style.cardheader}>
                            <Cell value-align={true} class={style.info}>
                                <template slot="custom">
                                    <img src={imageUrl || IMGuser} alt="" class={style.userImg} onClick={this.showTentpop} />
                                    <div class={style.infoname}>
                                        <span class={style.infoUser}>{realName}</span>
                                        <div class={style.levelBox}>
                                            <span class={style.userLevle}>{currentRoleName}</span>
                                            <img src={IMGswitchTip} alt="" class={style.switchTip} onClick={this.changeRole} />
                                        </div>
                                    </div>
                                    <img src={IMGsearch} alt="" class={style.IMGSearch} onClick={this.changeSearch} />
                                </template>
                            </Cell>
                            <img src={IMGbackground} alt="" class={style.background} />
                        </div>
                        <div class={style.applications}>
                            {
                                this.arr.map((item, groupIndex) => {
                                    return (
                                        <div class={style.fisrtGroup} key={groupIndex}>
                                            {
                                                <div class={style.fisrtGroupTitle}>
                                                    {item.name}
                                                </div>
                                            }
                                            {
                                                item.funcs.length > 0 ?
                                                    (<div class={style.fisrtGroupContent1}>
                                                        {
                                                            item.funcs.map((item, ffuncsIndex) => {
                                                                return (
                                                                    <div class={style.fisrtGroupFucsCell} key={ffuncsIndex}>
                                                                        <img class={style.fisrtFuncIcon} src={item.funcUrl || IMGdefault} />
                                                                        <div class={style.fisrtFuncName}>{item.name}</div>
                                                                    </div>)
                                                            })
                                                        }
                                                    </div>)
                                                    : ""
                                            }
                                            {
                                                item.menus.length > 0 ?
                                                    <div class={style.menus2}>
                                                        <Tabs vModel={this.secondMenu[groupIndex]} color="#0840F8" slider-width={17}>
                                                            {
                                                                item.menus.map((item, indexa) => {
                                                                    return <Tab title={item.name} key={indexa}>
                                                                        {
                                                                            item.funcs.length > 0 ?
                                                                                (<div class={style.fisrtGroupContent}>
                                                                                    {
                                                                                        item.funcs.map((item, sfuncs) => {
                                                                                            return (
                                                                                                <div class={style.fisrtGroupFucsCell} key={sfuncs}>
                                                                                                    <img class={style.fisrtFuncIcon} src={item.funcUrl || IMGdefault}></img>
                                                                                                    <div class={style.fisrtFuncName}>{item.name}</div>
                                                                                                </div>)
                                                                                        })
                                                                                    }
                                                                                </div>)
                                                                                : ""
                                                                        }
                                                                        {
                                                                            item.menus.length > 0 ? <div class={style.thirdMenu}>
                                                                                {

                                                                                    <Tabs vModel={this.thirdMenu[groupIndex][indexa]} color="#0840F8">
                                                                                        {
                                                                                            item.menus.map((item, indexb) => {
                                                                                                return <Tab title={item.name} key={indexb}>
                                                                                                    {
                                                                                                        item.funcs.length > 0 ?
                                                                                                            (<div class={style.fisrtGroupContent}>
                                                                                                                {
                                                                                                                    item.funcs.map((item, tfuncs) => {
                                                                                                                        return (
                                                                                                                            <div class={style.fisrtGroupFucsCell} key={tfuncs} onClick={() => {
                                                                                                                                this.funcsclick()
                                                                                                                            }}>
                                                                                                                                <img class={style.fisrtFuncIcon} src={item.funcUrl || IMGdefault}></img>
                                                                                                                                <div class={style.fisrtFuncName}>{item.name}</div>
                                                                                                                            </div>)
                                                                                                                    })
                                                                                                                }
                                                                                                            </div>)
                                                                                                            : ""
                                                                                                    }
                                                                                                </Tab>
                                                                                            })
                                                                                        }
                                                                                    </Tabs>
                                                                                }
                                                                            </div> : null
                                                                        }

                                                                    </Tab>
                                                                })
                                                            }
                                                        </Tabs>
                                                    </div> : ''
                                            }
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                </View >
                <Popup position="top" vModel={this.showSearch} >
                    <div class={style.searchBox}>
                        <img src={IMGclear} alt="" class={style.searchImg} onClick={() => {
                            this.keyWord = ''
                        }} />
                        <Search vModel={this.keyWord}></Search>
                        <span class={style.exitPop} onClick={() => {
                            this.changeSearch()
                        }}>取消</span>
                    </div>
                    <div class={style.searchContent} onClick={() => {
                        this.changeSearch()
                    }}>
                        <div class={style.select}>
                            {
                                this.includeArr.map((item, index) => {
                                    return (
                                        <div class={style.bottoma}>
                                            <div class={style.bottomdiv}>
                                                <img src={item.funcUrl || IMGdefault} alt="" class={style.funcUrl || IMGdefault} />
                                                <p key={index} domPropsInnerHTML={item.name}>
                                                    {item.name}
                                                </p>
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                </Popup>
                <Popup position="left" vModel={this.showTent}>
                    <PopLeft userParams={this.userParams} tentArrt={this.tentArr} vOn:refresh={this.init} vOn:modal={() => {
                        this.exitClick()
                    }}></PopLeft>
                </Popup>
                <Popup position="bottom" vModel={this.showRole} >
                    <div>
                        <div class={style.bottomBox}>
                            <div class={style.name}>
                                <span>切换角色</span>
                                <img src={IMGexit} alt="" class={style.exit} onClick={() => {
                                    this.showRole = false
                                }} />
                            </div>
                        </div>
                        {
                            this.roleArr.map((item, index) => {
                                return (<div class={style.rolist}>
                                    <Cell value-align={true} onClick={() => {
                                        this.changRole(index, item.code)
                                    }}>
                                        <template slot="title">
                                            <span class={item.selected ? style.roleChooseText : style.roleText}>{item.value}</span>
                                        </template>
                                        <template slot="value">{
                                            item.selected ? <img src={IMGsuccess} alt="" class={style.IMGsuccess} /> : null
                                        }
                                        </template>
                                    </Cell>
                                </div>)
                            })
                        }
                    </div>
                </Popup>
                <div class={style.exitLoginBox}>
                    {
                        this.showExit ? <div class={style.exitmoal}>
                            <div>  <div class={style.exitBox}>
                                <div class={style.exitText}>确认退出登录?</div>
                                <div class={style.exitSure}>
                                    <div class={style.exit} onClick={() => {
                                        this.exitClick()
                                    }}>取消</div>
                                    <div class={style.sure} onClick={() => {
                                        this.exitLogin()
                                    }}>确认退出</div>
                                </div>
                            </div></div>
                        </div> : ""
                    }
                </div>
            </div >
        )
    },
}
